//
// Created by changlei on 2022/4/26.
//

import Foundation
import Photos
import Kingfisher
import SafariServices


class Modules {
    static func openBrowser(_ url: String) {
        AppDelegate.shared.open(URL(string: url)!)
    }

    static func copy(_ value: String?) {
        UIPasteboard.general.string = value
    }

    static func share(_ url: String) {
        Modules.share(URL(string: url))
    }

    static func share(_ url: URL?) {
        if let topViewController = AppDelegate.default.topViewController, let url = url {
            let controller = UIActivityViewController(activityItems: [url], applicationActivities: nil)
            topViewController.present(controller, animated: true)
        }
    }

    static func saveToPhoto(_ url: String) {
        PHPhotoLibrary.requestAuthorization { status in
            if status != PHAuthorizationStatus.authorized {
                return
            }
            ImageDownloader.default.downloadImage(with: URL(string: url)!) { result in
                let data = try! result.get().originalData
                PHPhotoLibrary.shared().performChanges {
                    PHAssetChangeRequest.creationRequestForAsset(from: UIImage(data: data)!)
                }
            }
        }
    }

    static func saveToReadingList(_ url: String) {
        try? SSReadingList.default()?.addItem(with: URL(string: url)!, title: nil, previewText: nil)
    }
}